<template>
  <div class="container">
    <div class="flexContent" v-if="tabActiveName === 'first'">
      <div class="top">
        <p class="line"><span>通道组编码：</span>{{ childrenData.code }}</p>
        <p class="line"><span>通道组名称：</span>{{ childrenData.name }}</p>
      </div>
      <div class="center">

        <el-button class="addBtn" @click="positionShowModel" :disabled="!Boolean(warehouseId) || !Boolean(regionId)"
          v-has="'aisle_addchannel'">新增通道</el-button>
        <el-button class="delBtn" :disabled="selectNum === 0" @click="delAisleById"
          v-has="'aisle_delchannel'">批量删除</el-button>
        已选中 {{ selectNum }} 行
      </div>
      <div class="table">
        <div>
          <el-table border class="tablebox" :data="tableData" style="width: 100%" max-height="568" size="medium"
            @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="55">
            </el-table-column>
            <el-table-column align="center" prop="code" label="通道编码">
            </el-table-column>
            <el-table-column align="center" prop="name" label="通道名称">
            </el-table-column>
            <el-table-column align="center" prop="count" label="关联仓位">
              <template slot-scope="{row}">
                <el-button @click="changeTab(row)" type="text">{{ row.count }}</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="200"
              v-if="$showFn(['aisle_movechannel', 'aisle_editchannel', 'aisle_delchannel'])">
              <template slot-scope="scope">
                <el-button @click="moveDialog(scope.row)" type="text"
                  v-has="'aisle_movechannel'">移位</el-button>
                <el-button @click="positionShowModel(scope.row)" type="text"
                  v-has="'aisle_editchannel'">修改</el-button>
                <el-button @click="$delFn('通道', delAisleById, scope.row.id)" type="text" style="color: red;"
                  v-has="'aisle_delchannel'">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="pagination">
        <el-pagination background :current-page.sync="page.pageNum" :page-sizes="$pageSizes"
          :page-size.sync="page.pageSize" layout="total, ->,sizes, prev, pager, next, jumper" :total="page.total"
          @size-change="pageSizeChange" @current-change="getAisleGroupDetail" />
      </div>
    </div>

    <div class="flexContent" v-else="tabActiveName === 'second'">
      <div class="top">
        <p class="line"><span>通道编码：</span>{{ aisleObj.code }}</p>
        <p class="line"><span>通道名称：</span>{{ aisleObj.name }}</p>
      </div>
      <div class="center">

        <el-button class="delBtn" :disabled="selectNum === 0" @click="$delFn('仓位', delPositionById)">批量删除</el-button>
        已选中 {{ selectNum }} 行
      </div>
      <div class="table">
        <div>
          <el-table border class="tablebox" :data="tableData" style="width: 100%" max-height="568" size="medium"
            @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="55">
            </el-table-column>
            <el-table-column align="center" prop="code" label="仓位编码">
            </el-table-column>
            <el-table-column align="center" prop="name" label="仓位名称">
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="200" v-if="$showFn(['posmove', 'posdel'])">
              <template slot-scope="scope">
                <el-button @click="positionMoveDialog(scope.row.id)" type="text"
                  v-has="'posmove'">移位</el-button>
                <el-button @click="$delFn('仓位', delPositionById, scope.row.id)" type="text" style="color: red;"
                 v-has="'posdel'">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="pagination">
        <el-pagination background :current-page.sync="page.pageNum" :page-sizes="$pageSizes"
          :page-size.sync="page.pageSize" layout="total, ->,sizes, prev, pager, next, jumper" :total="page.total"
          @size-change="pageSizeChange2" @current-change="getPositionByAisle" />
      </div>
    </div>

    <!-- 添加或修改通道组的弹窗 -->
    <el-dialog destroy-on-close :title="aisleId ? '修改通道' : '新增通道'" :visible.sync="positionAddOrEditDialog" width="30%">
      <el-form ref="positionForm" :model="positionForm" :rules="positionRules" label-width="100px">
        <el-form-item label="通道名称：" prop="name">
          <el-input v-clearEmoji v-model="positionForm.name" placeholder="请输入..."/>
        </el-form-item>
        <el-form-item label="通道编码：" prop="code">
          <el-input v-clearEmoji v-model="positionForm.code" placeholder="请输入..."/>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button class="celBtn" @click="positionCancleDialog">取 消</el-button>
        <el-button class="addBtn" @click="positionSubmit('positionForm')">确 定</el-button>
      </div>
    </el-dialog>



    <el-dialog :title="'通道移位'" :visible.sync="moveAisle" width="30%">
      <el-form ref="aisleForm" :model="aisleForm" :rules="aisleRules" label-width="120px">
        <el-form-item label="通道组名称：" prop="groupId">
          <el-select v-model="aisleForm.groupId" placeholder="请选择目标通道组">
            <el-option v-for="item in aisleGroupList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button class="celBtn" @click="positionCancleDialog">取 消</el-button>
        <el-button class="addBtn" @click="moveSubmit('aisleForm')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="'仓位移位'" :visible.sync="positionMoveAisle" width="30%">
      <el-form ref="positionAisleForm" :model="positionAisleForm" :rules="positionAisleRules" label-width="120px">
        <el-form-item label="通道名称：" prop="aisleId">
          <el-cascader v-model="positionAisleForm.aisleId" :props="lazyAisle" 
            placeholder="请选择目标通道"></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button class="celBtn" @click="positionCancleDialog">取 消</el-button>
        <el-button class="addBtn" @click="positionMoveSubmit('positionAisleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { reqDelPositionById } from '@/api/warehouse';
import { reqAisleList, reqAddAisle, reqDelAisleById, reqDelMoreAisle, reqAisleGroupListInfo, reqMoveAisle, reqEditAisleById, reqPositionByAisle, reqAisleByAisleGroupId, reqPositionMove } from "@/api/storage"
export default {
  name: 'ChildrenTreeNode',
  // 区域ID
  props: ['childrenId', 'childrenData'],
  // childrenId 通道组id
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      // tab选项类型
      tabActiveName: 'first',
      // 仓库ID
      warehouseId: '',
      // 区域id
      regionId: '',
      // 当前选中数量
      selectNum: 0,
      idList: [],

      // 通道对应id
      positionId: '',
      // 移位弹窗
      moveAisle: false,
      // 仓位移位弹窗
      positionMoveAisle: false,
      // 移位通道id
      aisleId: '',
      aisleObj: {},
      // 添加通道弹窗
      positionAddOrEditDialog: false,
      // 添加通道表单
      positionForm: {
        name: '',
        code: '',
      },
      positionAisleForm: {
        aisleId: '',
      },
      positionAisleRules: {
        aisleId: [{
          required: true, message: '请选择通道', trigger: 'blur'
        }]
      },
      aisleForm: {
        groupId: '',
      },
      aisleGroupList: [],
      aisleRules: {
        groupId: [{
          required: true, message: '请选择通道组', trigger: 'blur'
        }]
      },
      tableData: [],
      positionRules: {
        name: [{
          required: true,
          message: '请输入通道名称',
          trigger: 'blur'
        }, {
          min: 0,
          max: 15,
          message: '通道名称长度不能超过15个字符',
          trigger: 'blur'
        }],
        code: [{
          required: true, message: '请输入通道编码', trigger: 'blur'
        }, {
          min: 0,
          max: 15,
          message: '通道编码长度不能超过15位数字',
          trigger: 'blur'
        }]
      },
      lazyAisle: {
        lazy: true,
        emitPath: false,
        lazyLoad: async (node, resolve) => {
          if (node.level == 0) {
            console.log(this);
            let res = await reqAisleGroupListInfo({ regionId: this.regionId });
            if (res.code === 200) {
              const nodes = res.data.map(item => ({
                value: item.id,
                label: item.name,
                leaf: node.level == 1
              }))
              resolve(nodes)
            }
          } else {
            let groupId = node.data.value;
            let res = await reqAisleByAisleGroupId({ groupId: groupId });
            if (res.code === 200) {
              const nodes = res.data.map(item => ({
                value: item.id,
                label: item.name,
                leaf: node.level == 1
              }))
              resolve(nodes)
            }
          }
        }
      }
    }
  },
  watch: {
    childrenId: {
      immediate: true,
      handler() {
        this.tabActiveName = 'first';
        this.page = {
          pageNum: 1,
          pageSize: 20,
          total: 0
        }
        this.getAisleGroupDetail();
      },
    },
  },
  methods: {
    async getAisleGroupDetail() {
      let { childrenId } = this;
      let { pageNum, pageSize } = this.page;
      let res = await reqAisleList({ groupId: childrenId, pageNum, pageSize });;
      if (res.code === 200) {
        this.warehouseId = this.childrenData.warehouseId;
        this.regionId = this.childrenData.regionId;
        this.tableData = res.data.list;
        this.page.total = res.data.total;
      }
    },
    async getPositionByAisle() {
      let res = await reqPositionByAisle({ aisleId: this.aisleObj.id, pageNum: this.page.pageNum, pageSize: this.page.pageSize });
      if (res.code === 200) {
        this.tableData = res.data.list;
        this.page.total = res.data.total;
      }
    },
    changeTab(row) {
      this.aisleObj = row;
      this.tabActiveName = "second";
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0
      }
      this.getPositionByAisle();
    },
    pageSizeChange() {
      this.page.pageNum = 1;
      this.getAisleGroupDetail();
    },
    pageSizeChange2() {
      this.page.pageNum = 1;
      this.getPositionByAisle();
    },
    // 显示选中几行
    handleSelectionChange(selectList) {
      this.idList = selectList.map(item => item.id);
      this.selectNum = selectList.length;
    },
    // 通道移位
    async moveDialog(row) {
      this.aisleForm.groupId = '';
      this.aisleId = row.id;
      let res = await reqAisleGroupListInfo({ regionId: this.regionId });
      if (res.code === 200) {
        this.aisleGroupList = res.data;
        this.aisleGroupList = this.aisleGroupList.filter(item => item.id != row.groupId);
      }
      this.moveAisle = true;
    },
    // 仓位移位
    positionMoveDialog(id) {
      this.positionAisleForm.aisleId = '';
      this.positionId = id;
      this.positionMoveAisle = true;
    },
    // 添加通道
    positionShowModel(aisleObj) {
      if (aisleObj.id !== undefined) {
        // 修改
        this.aisleId = aisleObj.id;
        this.positionForm = { name: aisleObj.name, code: aisleObj.code }
      } else {
        this.aisleId = '';
        this.positionForm = { name: '', code: '' }
      }
      this.positionAddOrEditDialog = true;
    },
    // 取消弹窗
    positionCancleDialog() {
      this.positionAddOrEditDialog = false;
      this.moveAisle = false;
      this.positionMoveAisle = false;
    },
    // 通道组移位
    moveSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let { aisleId } = this;
          let obj = { ...this.aisleForm, id: aisleId };
          let res = await reqMoveAisle(obj);
          if (res.code === 200) {
            this.$message.success('移位成功');
            if (this.tableData.length === 1 && this.page.pageNum > 1) this.page.pageNum--;
            this.moveAisle = false;
            // 重新加载列表
            this.getAisleGroupDetail();
          } else {
            // this.$message.error(res.message)
          }
        } else {
          this.$message.warning('请检查填写的信息')
          return false;
        }
      });
    },
    // 添加通道提交
    positionSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let { warehouseId, regionId, childrenId, aisleId } = this;
          let obj = { ...this.positionForm, warehouseId, regionId, groupId: childrenId };
          let res = {};
          if (aisleId) {
            res = await reqEditAisleById({ id: aisleId, ...obj });
          } else {
            res = await reqAddAisle(obj);
          }
          if (res.code === 200) {
            this.$message.success(aisleId ? '修改成功' : '添加成功');
            this.positionAddOrEditDialog = false;
            // 重新加载列表
            this.getAisleGroupDetail();
          } else {
            // this.$message.error(res.message)
          }
        } else {
          this.$message.warning('请检查填写的信息')
          return false;
        }
      });
    },
    // 仓位移位提交
    positionMoveSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let obj = { ...this.positionAisleForm, id: this.positionId };
          let res = await reqPositionMove(obj);
          if (res.code === 200) {
            this.$message.success('移位成功');
            if (this.tableData.length === 1 && this.page.pageNum > 1) this.page.pageNum--;
            this.positionMoveAisle = false;
            this.getPositionByAisle();
          } else {
            // this.$message.error(res.message)
          }
        } else {
          this.$message.warning('请检查填写的信息')
          return false;
        }
      });
    },
    // 删除仓位
    async delPositionById(id) {
      let res = {};
      if (typeof id == 'string') {
        res = await reqDelPositionById({ idList: [id] });
      } else {
        res = await reqDelPositionById({ idList: this.idList });
      }
      if (res.code === 200) {
        this.$message.success('删除成功');
        if ((this.tableData.length === this.idList.length || this.tableData.length === 1) && this.page.pageNum > 1) this.page.pageNum--;
        this.idList = [];
        // 重新加载列表
        this.getPositionByAisle();
      } else {
        // this.$message.error(res.message)
      }
    },
    // 删除通道
    async delAisleById(id) {
      let res = {};
      if (typeof id == 'string') {
        res = await reqDelAisleById({ id });
      } else {
        res = await reqDelMoreAisle({ idList: this.idList });
      }
      if (res.code === 200) {
        this.$message.success('删除成功');
        if ((this.tableData.length === this.idList.length || this.tableData.length === 1) && this.page.pageNum > 1) this.page.pageNum--;
        this.idList = [];
        // 重新加载列表
        this.getAisleGroupDetail();
      } else {
        // this.$message.error(res.message)
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.container {
  height: 100%;

  .flexContent {
    height: 100%;
    width: 100%;

    .top {
      display: flex;

      .line {
        width: 50%;
      }
    }
  }
}
</style>